const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const MongoClient = require('mongodb').MongoClient
const ejsexcel = require('ejsexcel')
const util = require('util')
const moment = require('moment')

const readFileAsync = util.promisify(fs.readFile);
const writeFileAsync = util.promisify(fs.writeFile);

const url = "mongodb://localhost:27017/";
const dbName = "data";

const requstPromise = (res) => {
    return new Promise((resolve, reject) => {
        resolve(res)
    })
}

/**
 * * 向指定的表中添加一条数据
 * @param {*} name
 * @param {*} data
 * @returns
 */
const insertData = (name, data) => {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, { useNewUrlParser: true }, (err, db) => {
            if (err) {
                resolve(err)
                throw err;
            }
            let dbo = db.db(dbName);
            let collection = dbo.collection(name);
            collection.insertOne({
                creatTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                ...data
            }, (err, result) => {
                if (err) {
                    resolve(err)
                    throw err;
                }
                resolve(result)
                db.close();
            });
        });
    })
}

/**
 * * 向指定的表中查找数据
 * @param {*} name
 * @param {*} data
 * @param {*} sort
 * @param {*} skip 跳过多少条数据
 * @param {*} limit 返回多少条数据 
 * @returns
 */
const findData = (name, data, sort = {}, skip = 0, limit = 9999999999999) => {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, function (err, db) {
            if (err) {
                resolve(err)
                throw err;
            }
            var dbo = db.db(dbName);
            let collection = dbo.collection(name);
            console.log(name, data, sort, skip, limit)
            collection.find(data).sort(sort).skip(skip).limit(limit).toArray((err, result) => {
                // collection.find(data).toArray((err, result) => {
                if (err) {
                    resolve(err)
                    throw err;
                }
                resolve(result)
                db.close();
            });
        });
    })
}

/**
 * * 向指定的表中查找数据
 * @param {*} name
 * @param {*} data
 * @returns
 */
const findOneData = (name, data, sort, skip, limit) => {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, function (err, db) {
            if (err) {
                resolve(err)
                throw err;
            }
            var dbo = db.db(dbName);
            let collection = dbo.collection(name);
            collection.findOne(data, (err, result) => {
                if (err) {
                    resolve(err)
                    throw err;
                }
                resolve(result)
                db.close();
            })
        });
    })
}

/**
 * * 向指定的表更新一条数据
 * @param {*} name
 * @param {*} data
 * @returns
 */
const updateData = (name, target, data) => {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, function (err, db) {
            if (err) {
                resolve(err)
                throw err;
            }
            var dbo = db.db(dbName);
            let collection = dbo.collection(name);
            collection.updateOne(target, {
                $set: {
                    updatedTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                    ...data
                }
            }, (err, result) => {
                if (err) {
                    resolve(err)
                    throw err;
                }
                resolve(result)
                db.close();
            });
        });
    })
}

/**
 * * 向指定的表删除一条数据
 * @param {*} name
 * @param {*} data
 * @returns
 */
const deleteOneData = (name, data) => {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, function (err, db) {
            if (err) {
                resolve(err)
                throw err;
            }
            var dbo = db.db(dbName);
            let collection = dbo.collection(name);
            console.log(data)
            collection.deleteOne(data, (err, result) => {
                if (err) {
                    resolve(err)
                    throw err;
                }
                resolve(result)
                db.close();
            });
        });
    })
}

/**
 * * 将指定数据生成 xlsx 文件并提供下载地址
 * @param {*} downloadName
 * @param {*} data
 * @param {*} fileName
 * @returns
 */
const downloadXlsx = (downloadName, data, fileName) => {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, function (err, db) {
            if (err) {
                resolve(err)
                throw err;
            }
            var dbo = db.db(dbName);
            dbo.collection(downloadName).find(data).toArray(async function (err, result) {
                if (err) {
                    resolve(err)
                    throw err;
                }
                //获得Excel模板的buffer对象
                const exlBuf = await readFileAsync(path.join(__dirname, "/../public/excel/posts.xlsx"));
                //用数据源(对象)data渲染Excel模板
                const exlBuf2 = await ejsexcel.renderExcel(exlBuf, result);
                const name = fileName ? fileName : new Date().valueOf()
                await writeFileAsync(path.join(`${__dirname}/../public/excel/${name}.xlsx`), exlBuf2);
                resolve(writeFileAsync)
                db.close();
            });
        });
    })
}

/*
** randomWord 产生任意长度随机字母数字组合
** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
** xuanfeng 2014-08-28
*/

const randomWord = (randomFlag, min, max) => {
    var str = "",
        range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    // 随机产生
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
        pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
}

const getPageQuery = (option) => {
    const { data = {}, pageIndex = 0, pageSize = 10 } = option
    let index = parseInt(pageIndex)
    if (index <= 0) {
        index = 0
    } else {
        index = index - 1
    }
    let skip = index * parseInt(pageSize)
    let limit = parseInt(pageSize)
    // 清除无用的信息
    for (let attr in data) {
        if (data[attr] == null || data[attr] == undefined || data[attr] == 'undefined') {
            delete data[attr]
        }
    }
    return { data, skip, limit }

}


const setLog = (str, result) => {
    console.log(str)
    console.log(result)
    console.log('————————————————————')
}


const creatMenu = (api, access_token) => {
    console.log(api)
    // , {
    //     "type": "view",
    //     "name": "活动抽奖",
    //     "url": "http://www.camluni.com/questions/luckyDraw",
    //     "sub_button": []
    // }
    api.post(`https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${access_token}`, {
        "button": [{
            "name": "预约试听课",
            "sub_button": [{
                "type": "view",
                "name": "预约试听课",
                "url": "http://cn.mikecrm.com/SKJ74EH",
                "sub_button": []
            }]
        }, {
            "name": "关于我们",
            "sub_button": [{
                "type": "view",
                "name": "官方网站",
                "url": "http://www.camluni.com/",
                "sub_button": []
            }, {
                "type": "view",
                "name": "课程介绍",
                "url": "https://mp.weixin.qq.com/s/-brMTGenVYN3GXYPiSgTig",
                "sub_button": []
            }, {
                "type": "view",
                "name": "文章目录",
                "url": "http://mp.weixin.qq.com/mp/homepage?__biz=MzI0NDI4NDYwNA==&hid=1&sn=170e510775f2f9eb52564fc1a71323ee&scene=18#wechat_redirect",
                "sub_button": []
            }, {
                "type": "view",
                "name": "联系我们",
                "url": "https://mp.weixin.qq.com/s/-6IXFaaowOq2DJ1ngrOn4A",
                "sub_button": []
            }, {
                "type": "view",
                "name": "卡墨微店",
                "url": "https://weidian.com/?userid=1343867711&spider_token=5e93&spider=seller.new_item_detail.shop_info_wrap.2",
                "sub_button": []
            }]
        }, {
            "name": "会员中心",
            "sub_button": [{
                "type": "view",
                "name": "我的主页",
                "url": "https://open.xgjssx.com/Jump/Page?name=main&terminal=1&app=wxbc2631875fcdbfb3",
                "sub_button": []
            }, {
                "type": "view",
                "name": "会员福利",
                "url": "https://mp.weixin.qq.com/s?__biz=MzI0NDI4NDYwNA==&mid=2247485401&idx=2&sn=5a0a39a0e3818c68007100ed18948d58&chksm=e9616a0ade16e31c02b44690b2f7bc198d1bcc71eab95fd637e050f1f3879f60fdeb67607eae&scene=18#rd",
                "sub_button": []
            }, {
                "type": "view",
                "name": "切换用户",
                "url": "https://open.xgjssx.com/Login/Change?terminal=1&app=wxbc2631875fcdbfb3",
                "sub_button": []
            }, {
                "type": "view",
                "name": "绑定新用户",
                "url": "https://open.xgjssx.com/Login/Index?terminal=1&app=wxbc2631875fcdbfb3",
                "sub_button": []
            }]
        }]
    }).then(createRes => {
        console.log(createRes)
    })
}

module.exports = {
    url,
    dbName,
    requstPromise,
    insertData,
    findData,
    findOneData,
    updateData,
    deleteOneData,
    downloadXlsx,
    randomWord,
    getPageQuery,
    creatMenu,
    setLog
}
